package cn.taobaoke.restful.service;

import cn.taobaoke.restful.domain.InviteCodeEntity;
import cn.taobaoke.restful.domain.InviteCodeRepository;
import cn.taobaoke.restful.exception.TBKException;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InviteCodeService {

    public InviteCodeEntity findByCode(final String code) {
        return inviteCodeRepository.findByCode(code).orElse(null);
    }

    @Transactional
    public Boolean consumeCode(final Long agentId, final String code) {
        Optional<InviteCodeEntity> codeOpt = inviteCodeRepository.findByCode(code);
        InviteCodeEntity entity = codeOpt.orElseThrow(() -> new TBKException("邀请码" + code + "不存在"));
        if (entity.getIsAssigned() != null && entity.getIsAssigned())
            return false;
        entity.setAgentId(agentId);
        entity.setIsAssigned(true);
        inviteCodeRepository.save(entity);
        return true;
    }

    private final @NonNull
    InviteCodeRepository inviteCodeRepository;
}
